package com.mvvm.start.base.utils

import android.content.Context
import android.os.Looper
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import com.mvvm.start.base.BaseApplication
import java.io.*

/**
 * @author lmy
 * @功能: 全局异常的捕获 并重启程序
 * @Creat 2021/7/7 1:24 下午
 * @Compony 465008238@qq.com
 */

class CrashHandler(private val context: Context) : Thread.UncaughtExceptionHandler {
    override fun uncaughtException(t: Thread, e: Throwable) {
        showToast()
//        Log.e("程序出现异常了", "Thread = ${t.name}Throwable = ${e.message}")
//        val stackTraceInfo = getStackTraceInfo(e)
//        Log.e("stackTraceInfo", stackTraceInfo)
//        saveThrowableMessage(stackTraceInfo)
    }

    /**
     * 获取错误的信息
     *
     * @param throwable
     * @return
     */
    private fun getStackTraceInfo(throwable: Throwable): String {
        var pw: PrintWriter? = null
        var writer = StringWriter()
        try {
            pw = PrintWriter(writer)
            throwable.printStackTrace(pw);
        } catch (e: Exception) {
            return "";
        } finally {
            pw?.close()
        }
        return writer.toString();
    }

    /**
     * 操作
     *
     * @param thread
     * @param e
     */
    private fun showToast() {
        Thread {
            Looper.prepare()
            "程序发生异常，正在重新启动。".toast()
            Looper.loop()
        }.start()

        restartApp()
    }

    /**
     * 重启应用
     */
    private fun restartApp() {
//        val intent = Intent(context, SplashADActivity::class.java)
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//        context.startActivity(intent)
//        Process.killProcess(Process.myPid()) //再此之前可以做些退出等操作
    }


    private val logFilePath =
        Environment.getExternalStorageDirectory().toString() + File.separator + "Android" +
                File.separator + "data" + File.separator + BaseApplication.application.packageName + File.separator + "crashLog"

    private fun saveThrowableMessage(errorMessage: String) {
        if (TextUtils.isEmpty(errorMessage)) {
            return
        }
        val file = File(logFilePath)
        if (!file.exists()) {
            val mkdirs = file.mkdirs()
            if (mkdirs) {
                writeStringToFile(errorMessage, file)
            }
        } else {
            writeStringToFile(errorMessage, file)
        }
    }

    private fun writeStringToFile(errorMessage: String, file: File) {
        Thread {
            var outputStream: FileOutputStream? = null
            try {
                val inputStream = ByteArrayInputStream(errorMessage.toByteArray())
                outputStream =
                    FileOutputStream(File(file, System.currentTimeMillis().toString() + ".txt"))
                var len = 0
                val bytes = ByteArray(1024)
                while (inputStream.read(bytes).also { len = it } != -1) {
                    outputStream.write(bytes, 0, len)
                }
                outputStream.flush()
                Log.e("程序出异常了", "写入本地文件成功：" + file.absolutePath)
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
            }
        }.start()
    }

}